package stock;
 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.hibernate.dialect.MySQLInnoDBDialect;
 
@SuppressWarnings("all")
public final class Common {

	/**
	 * 两位小数
	 */
	public static DecimalFormat df1 = new DecimalFormat("######0.000");

	public static String getTime() {
		DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
		Date date = Calendar.getInstance().getTime();
		TimeZone srcTimeZone = TimeZone.getTimeZone("EST");
		TimeZone destTimeZone = TimeZone.getTimeZone("GMT+8");
		// return VeDate.dateTransformBetweenTimeZone(date, formatter,
		// srcTimeZone, destTimeZone).toString();
		return Calendar.getInstance().getTime().toLocaleString();
	}

	public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

	public static String dateTransformBetweenTimeZone(Date sourceDate, DateFormat formatter, TimeZone sourceTimeZone,
			TimeZone targetTimeZone) {
		Long targetTime = sourceDate.getTime() - sourceTimeZone.getRawOffset() + targetTimeZone.getRawOffset();
		return Common.getTime(new Date(targetTime), formatter);
	}

	public static String getTime(Date date, DateFormat formatter) {
		return formatter.format(date);
	}

	public static String getTime(Long l) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(new Date(l));
	}

	/**
	 * 得到当前系统日期的格式化
	 * 
	 * @return
	 */
	public static Long getTime1() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date beginTime2 = null;
		try {
			beginTime2 = Calendar.getInstance().getTime();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return beginTime2.getTime();
	}

	 

	/**
	 * 功能:压缩多个文件成一个zip文件
	 * <p>
	 * 作者 陈亚标 Jul 16, 2010 10:59:40 AM
	 * 
	 * @param srcfile ：源文件列表
	 * @param zipfile ：压缩后的文件
	 */
	public static File zipFiles(File[] srcfile, File zipfile) {
		byte[] buf = new byte[1024];
		try {
			// ZipOutputStream类：完成文件或文件夹的压缩
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
			List<String> list = new ArrayList<String>();
			for (int i = 0; i < srcfile.length; i++) {
				FileInputStream in = new FileInputStream(srcfile[i]);
				String zipName = srcfile[i].getName().substring(37, srcfile[i].getName().length());
				if (list.contains(zipName)) {
					zipName = i + zipName;
					list.add(zipName);
				} else {
					list.add(zipName);
				}
				out.putNextEntry(new ZipEntry(zipName));
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				out.closeEntry();
				in.close();
			}
			out.close();
			// System.out.println("压缩完成.");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return zipfile;
	}

	/**
	 * 加载以下配置文件
	 */
	public void loadFileConfig() {

	}

	 
	 

	/**
	 * 字符转时间的Long
	 * 
	 * @param str
	 * @return
	 * @throws ParseException
	 */
	public static Long getTimeLong(String str) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return sdf.parse(str).getTime();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			System.out.println("-------------------时间转换格式出错------------------");
			return new Long(0);
		}
	}

	/**
	 * 创建指定数量的随机字符串
	 * 
	 * @param length
	 * @return
	 */
	public static String createRandom(int length) {
		String retStr = "";
		String strTable = "1234567890";
		int len = strTable.length();
		boolean bDone = true;
		do {
			retStr = "";
			int count = 0;
			for (int i = 0; i < length; i++) {
				double dblR = Math.random() * len;
				int intR = (int) Math.floor(dblR);
				char c = strTable.charAt(intR);
				if (('0' <= c) && (c <= '9')) {
					count++;
				}
				retStr += strTable.charAt(intR);
			}
			if (count >= 2) {
				bDone = false;
			}
		} while (bDone);

		return retStr;
	}

	/**
	 * java下载
	 * 
	 * @param remoteFilePath
	 * @param localFilePath
	 */
	public static void downloadFile(String remoteFilePath, String localFilePath) {
		URL urlfile = null;
		HttpURLConnection httpUrl = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		File f = new File(localFilePath);
		try {
			if (!f.isFile()) {
				f.createNewFile();
			}
			urlfile = new URL(remoteFilePath);
			httpUrl = (HttpURLConnection) urlfile.openConnection();
			httpUrl.connect();
			bis = new BufferedInputStream(httpUrl.getInputStream());
			bos = new BufferedOutputStream(new FileOutputStream(f));
			int len = 2048;
			byte[] b = new byte[len];
			while ((len = bis.read(b)) != -1) {
				bos.write(b, 0, len);
			}
			bos.flush();
			bis.close();
			httpUrl.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bis.close();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 增加图片到qq服务器
	 * 
	 * @param urlString
	 * @return
	 * @throws IOException
	 */
	public String addImageForQQ(String urlString) throws IOException {
		URL urlfile = null;
		HttpURLConnection httpUrl = null;
		BufferedOutputStream bos = null;
		urlfile = new URL(urlString);
		httpUrl = (HttpURLConnection) urlfile.openConnection();
		httpUrl.connect();
		InputStream bis = httpUrl.getInputStream();
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[4096];
		int n = 0;
		while (-1 != (n = bis.read(buffer))) {
			output.write(buffer, 0, n);
		}
		byte[] bbb = output.toByteArray();
		String str = "";
		try {
			// str = QQImage.QQupload(bbb);
			System.out.println(str);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * 从网络Url中下载文件,增加到qq服务器
	 * 
	 * @param urlStr
	 * @param fileName
	 * @param savePath
	 * @throws IOException
	 */
	public static boolean downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 设置超时间为3秒
		conn.setConnectTimeout(3 * 1000);
		// 防止屏蔽程序抓取而返回403错误
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

		// 得到输入流
		InputStream inputStream = conn.getInputStream();
		// 获取自己数组
		byte[] getData = readInputStream(inputStream);

		// 文件保存位置
		File saveDir = new File(savePath);
		if (!saveDir.exists()) {
			saveDir.mkdir();
		}
		File file = new File(saveDir + File.separator + fileName);
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(getData);
		if (fos != null) {
			fos.close();
		}
		if (inputStream != null) {
			inputStream.close();
		}

		return true;

	}

	/**
	 * 从输入流中获取字节数组
	 * 
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public static byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}

	public static String httpGet(String url)
			throws ClientProtocolException, IOException, URISyntaxException, ParseException {
		HttpClient httpclient = new DefaultHttpClient();
		String result = "";
		try {
			// 连接超时
			httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
			// 读取超时
			httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);

			HttpGet hg = new HttpGet(url);
			// 模拟浏览器
			hg.addHeader("User-Agent",
					"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");
			String charset = "UTF-8";
			hg.setURI(new java.net.URI(url));
			HttpResponse response = httpclient.execute(hg);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				charset = getContentCharSet(entity);
				// 使用EntityUtils的toString方法，传递编码，默认编码是ISO-8859-1
				result = EntityUtils.toString(entity, charset);
			}

		} finally {
			httpclient.getConnectionManager().shutdown();
		}
		return result;
	}

	/**
	 * 默认编码utf -8 Obtains character set of the entity, if known.
	 * 
	 * @param entity must not be null
	 * @return the character set, or null if not found
	 * @throws ParseException           if header elements cannot be parsed
	 * @throws IllegalArgumentException if entity is null
	 */
	public static String getContentCharSet(final HttpEntity entity) throws ParseException {

		if (entity == null) {
			throw new IllegalArgumentException("HTTP entity may not be null");
		}
		String charset = null;
		if (entity.getContentType() != null) {
			HeaderElement values[] = entity.getContentType().getElements();
			if (values.length > 0) {
				NameValuePair param = values[0].getParameterByName("charset");
				if (param != null) {
					charset = param.getValue();
				}
			}
		}

		if (StringUtils.isEmpty(charset)) {
			charset = "UTF-8";
		}
		return charset;
	}

	public static String sendGet1(String url) {
		HttpGet request = new HttpGet(url);
		String result = "";
		try {
			HttpResponse response = HttpClients.createDefault().execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(response.getEntity());
			}
		} catch (Exception e) {

		}
		return result;
	}

	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// // 遍历所有的响应头字段
			// for (String key : map.keySet()) {
			// System.out.println(key + "--->" + map.get(key));
			// }
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	// public static void main(String[] args) {
	// changeToMp3("C:\\Users\\liuyang\\Desktop/-dkjckStYBoIUf-Mqy799-IRfrvXRrVcncrb8_v7L20pPZNBDbiPnXmQb9iwCBrb.amr",
	// "C:\\Users\\liuyang\\Desktop/aa.mp3");
	// }

	 

	/**
	 * 解决中英文 长度的问题
	 * 
	 * @param name
	 * @param endcoding
	 * @return
	 * @throws Exception
	 */
	public static int getChineseLength(String name, String endcoding) throws Exception {
		int len = 0; // 定义返回的字符串长度
		int j = 0;
		// 按照指定编码得到byte[]
		byte[] b_name = name.getBytes(endcoding);
		while (true) {
			short tmpst = (short) (b_name[j] & 0xF0);
			if (tmpst >= 0xB0) {
				if (tmpst < 0xC0) {
					j += 2;
					len += 2;
				} else if ((tmpst == 0xC0) || (tmpst == 0xD0)) {
					j += 2;
					len += 2;
				} else if (tmpst == 0xE0) {
					j += 3;
					len += 2;
				} else if (tmpst == 0xF0) {
					short tmpst0 = (short) (((short) b_name[j]) & 0x0F);
					if (tmpst0 == 0) {
						j += 4;
						len += 2;
					} else if ((tmpst0 > 0) && (tmpst0 < 12)) {
						j += 5;
						len += 2;
					} else if (tmpst0 > 11) {
						j += 6;
						len += 2;
					}
				}
			} else {
				j += 1;
				len += 1;
			}
			if (j > b_name.length - 1) {
				break;
			}
		}
		return len;
	}

	public static String getNull(Object obj) {
		if (obj == null) {
			return "";
		} else {
			return obj.toString();
		}
	}

	/**
	 * 请求服务，并传参数
	 * 
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String httpPost(String url, List<NameValuePair> params) throws Exception {
		String result = "";
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream instreams = entity.getContent();
				result = convertStreamToString(instreams);

			}
		} catch (Exception e) {
			throw e;
		}
		return result;
	}

	/**
	 * 
	 * 远程返回的string
	 * 
	 * @param is
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
		// BufferedReader reader = new BufferedReader(new
		// InputStreamReader(is));
		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	/**
	 * 
	 * 根据坐标得名字
	 * 
	 * @param list
	 * @return
	 * @throws Exception
	 */
	public static String getNameAddressList(List<String> list) throws Exception {
		String url = "http://restapi.amap.com/v3/geocode/regeo?output=json&key=53af259f31386633b25ae8c1c97d8361&radius=500&extensions=base";
		List list1 = new ArrayList<NameValuePair>();
		String str = "";
		for (int i = 0; i < list.size(); i++) {
			if (i == list.size() - 1) {
				str += list.get(i);
			} else {
				str += list.get(i) + "|";
			}
		}
		list1.add(new BasicNameValuePair("location", str));
		list1.add(new BasicNameValuePair("batch", "true"));
		return Common.httpPost(url, list1);
	}

	 

	/**
	 * 
	 * 长字符串转IP
	 * 
	 * @param phoneNo
	 * @return
	 */
	public static String getPretendip(String phoneNo) {
		String ip = "";
		byte[] ip_byte = new byte[6];
		if (phoneNo.length() == 11) {
			ip_byte[0] = Byte.valueOf(phoneNo.substring(0, 1));
			ip_byte[1] = Byte.valueOf(phoneNo.substring(1, 3));
			ip_byte[2] = Byte.valueOf(phoneNo.substring(3, 5));
			ip_byte[3] = Byte.valueOf(phoneNo.substring(5, 7));
			ip_byte[4] = Byte.valueOf(phoneNo.substring(7, 9));
			ip_byte[5] = Byte.valueOf(phoneNo.substring(9, 11));

			if ((ip_byte[1] >= 30) && (ip_byte[1] < 46)) {
				ip_byte[1] = (byte) (ip_byte[1] - 30);
				if ((ip_byte[1] & 0x08) == 0x08) {
					ip += (ip_byte[2] + 0x80) + ".";

				} else {
					ip += (ip_byte[2]) + ".";
				}
				if ((ip_byte[1] & 0x04) == 0x04) {
					ip += (ip_byte[3] + 0x80) + ".";

				} else {
					ip += (ip_byte[3]) + ".";
				}
				if ((ip_byte[1] & 0x02) == 0x02) {
					ip += (ip_byte[4] + 0x80) + ".";

				} else {
					ip += (ip_byte[4]) + ".";
				}
				if ((ip_byte[1] & 0x01) == 0x01) {
					ip += (ip_byte[5] + 0x80);

				} else {
					ip += (ip_byte[5]);
				}

			} else if ((ip_byte[1] >= 50) && (ip_byte[1] < 60)) {
				ip_byte[1] = (byte) ((ip_byte[1] - 30) & 0x0f);
				if ((ip_byte[1] & 0x08) == 0x08) {

					ip += (ip_byte[2] + 0x80) + ".";
				} else {
					ip += (ip_byte[2]) + ".";
				}
				if ((ip_byte[1] & 0x04) == 0x04) {

					ip += (ip_byte[3] + 0x80) + ".";
				} else {
					ip += (ip_byte[3]) + ".";
				}
				if ((ip_byte[1] & 0x02) == 0x02) {

					ip += (ip_byte[4] + 0x80) + ".";
				} else {
					ip += (ip_byte[4]) + ".";
				}
				if ((ip_byte[1] & 0x01) == 0x01) {

					ip += (ip_byte[5] + 0x80);
				} else {
					ip += (ip_byte[5]);
				}

			}

		}
		return ip;
	}

	 
 

	public static void main(String[] args) {
	 

	}

	public static String gettxt2String(String path) {
		File file = new File(path);
		StringBuilder result = new StringBuilder();

		try {
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader ifs = new InputStreamReader(fis, "UTF-8");
			BufferedReader br = new BufferedReader(ifs);// 构造一个BufferedReader类来读取文件
			String s = null;
			while ((s = br.readLine()) != null) {// 使用readLine方法，一次读一行
				result.append(System.lineSeparator() + s);
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.toString();
	}

}
